let express = require("express");

const { render } = require("../tool/read")

let Router = express.Router();

const { searchOne } = require("../tool/db")

// /reg/
Router.get("/", async function (req, res) {
    var data = await render("/html/register.html");
    res.end(data);
})


// /reg/isExist
Router.get("/isExistUser", async function (req, res) {
    res.writeHead(200, { "Content-Type": "text/json;charset=utf-8" });

    var { user } = req.query;
    console.log(user);

    var obj = {};

    if (user) {
        try {
            var sql = `select * from userinfo where user= '${user}'`;
            var data = await searchOne(sql)
            console.log(data);
            if (!data) {
                obj.status = true;
                obj.msg = "OK!";
            } else {
                obj.status = false;
                obj.msg = "用户名已存在";
            }
        } catch (err) {
            obj.status = false;
            obj.msg = err.sqlMessage;
            obj.sql = err.sql;
        }
    } else {
        obj.status = false;
        obj.msg = "请传入完整参数";
    }
    res.json(obj);
    // res.write(JSON.stringify(obj));
    // res.end();
})



/* Router.get("/isExistUser", function (req, res) {
    res.writeHead(200, { "Content-Type": "text/json;charset=utf-8" });

    var { user } = req.query;
    console.log(user);

    var obj = {};

    if (user) {
        var sql = `select * form userinfo where user= '${user}'`;
        searchOne(sql).then(data => {
            console.log(data);
            obj.status = true;
            obj.msg = "OK!";
            obj.data = data;
            res.write(JSON.stringify(obj));
            res.end();
        }).catch(err => {
            console.log(222222222);
            obj.status = false;
            obj.msg = err.sqlMessage;
            obj.sql = err.sql;
            res.write(JSON.stringify(obj));
            res.end();
        })

    } else {
        obj.status = false;
        obj.msg = "请传入完整参数";
        res.write(JSON.stringify(obj));
        res.end();
    }

}) */

// !!!!!!!!!!!!!!
module.exports = Router;